/*
 * LoginCheckListener.java
 * 
 * Copyright (c) 2011 Administrator. 
 * 
 * This file is part of RMS.
 * 
 * RMS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * RMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with RMS.  If not, see <http ://www.gnu.org/licenses/>.
 */
package com.itrustsolution.rms.pagecontroller;

import com.itrustsolution.rms.managedbean.UserInfoBean;
import com.itrustsolution.rms.util.JSFUtil;
import com.itrustsolution.rms.util.RmsUtil;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 * Force user to login
 * @author Administrator
 */
public class LoginCheckListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent phaseEvent) {
        FacesContext fc = phaseEvent.getFacesContext();
        System.out.println("viewId = " + fc.getViewRoot().getViewId());
        if (fc.getViewRoot().getViewId().equals("/login.xhtml")) {
            return;
        }

        UserInfoBean userInfo = (UserInfoBean) JSFUtil.getManagedBeanValue("userInfo");
        if (userInfo == null || RmsUtil.isNullOrEmpty(userInfo.getLoginName())) {
            System.out.println("qqq7707 restoreViewListener needLogin");
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "login");
        } else {
            System.out.println("qqq7708 restoreViewListener " + userInfo.getLoginName() + " has Login");
            return;
//            NavigationHandler nh = fc.getApplication().getNavigationHandler();
//            nh.handleNavigation(fc, null, "mainpage");
        }
    }

    @Override
    public void beforePhase(PhaseEvent phaseEvent) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.INVOKE_APPLICATION;
    }
}
